app.controller('inspectionCtrl', function($scope, httpService, $timeout, toaster,$localStorage){
    var url = "/inspection";
    $scope.MissionLevel = wtSys.Emun.MissionLevel;//紧急程度
    $scope.MissionMold = wtSys.Emun.MissionMold;//巡查类别
    $scope.searchList = [
        {
            "typeName" : "类型1",
            "typeList" : [{"Id" : 1, "Name" : "test1"}, {"Id" : 2, "Name" : "test2"}, {
                "Id" : 3,
                "Name" : "test3"
            }, {"Id" : 4, "Name" : "test4"}]
        },
        {
            "typeName" : "类型2",
            "typeList" : [{"Id" : 5, "Name" : "test5"}, {"Id" : 6, "Name" : "test6"}, {"Id" : 7, "Name" : "test7"}]
        }
    ];
    // 初始化查询变量
    $scope.initParam = function(){
        $scope.inspectionList = [];
        $scope.page = 1;
        $scope.busy = false;
        $scope.limit = 10;
        $scope.isGetDetailTag = true;//第一次默认加载第一条记录右侧信息
    }
    $scope.edit = function(item, index){
        if(item && item.MissionStatus == 1){
            return
        }
        // 还原表单以及表单值
        $scope.inspectionForm.$setPristine();
        if(item){
            $scope.id = item.Id;
            $scope.index = index;
            $scope.editModalTitle = "修改巡查任务";
            $scope.getinspectionDetail(item.Id);
        } else {
            $scope.id = null;
            $scope.index = null;
            $scope.inspectionModel = {
                "MissionLevel" : null,
                "MissionMold" : null,
                "Note" : "",
                "Remark" : "",
                "HandlerId" : "",
                "DeviceId" : ['fb3ffe494c274536962b9df7a3849278']
            }
            $scope.editModalTitle = "新增巡查任务";
        }
        $('#editModal').modal('show');
    };
    //任务表单提交
    $scope.inspectionFormSubmit = function(){
        $scope.inspectionForm.$invalid = true;
        var path = url;
        var type = "POST";
        if($scope.id){
            path = url + "/" + $scope.id;
            type = "PUT";
        }
        httpService.request(type, path, $scope.inspectionModel, function(result){
                $scope.inspectionForm.$invalid = false;
                toaster.pop("success", "提示", result.message);
                $('#editModal').modal('hide');
                // 更新列表数据
                var arr = $scope.inspectionList;
                if($scope.index != null && $scope.index >= 0){
                    arr[$scope.index] = result.data;//index存在直接更新
                } else {
                    arr.unshift(result.data);
                    $scope.activeId = result.data.Id;
                }
                $scope.inspectionList = arr;
            }
        )
    }
    //删除任务弹框处理
    $scope.del = function(item, index){
        $scope.index = index;
        $scope.delModel = angular.copy(item);
        $('#delModal').modal('show');
    };
    //确认删除任务
    $scope.delConfirm = function(){
        $('#delModal').modal('hide');
        var path = url + '/' + $scope.delModel.Id;
        httpService.request("DELETE", path, null, function(result){
            toaster.pop("success", "提示", result.message);
            // 更新列表数据
            var arr = $scope.inspectionList;
            arr.splice($scope.index, 1);
            $scope.inspectionModelList = arr;
            //如果删除的是第一条数据,删除成功后重新设置activeId的值
            if($scope.index == 0){
                $scope.activeId = arr[0] ? arr[0].Id : null;
            }
        });
    }
    // 日期组件
    $scope.openStart = function($event){
        $event.preventDefault();
        $event.stopPropagation();
        $scope.openStarted = true;
    };
    $scope.openEnd = function($event){
        $event.preventDefault();
        $event.stopPropagation();
        $scope.openEnded = true;
    };
    //获取任务列表
    $scope.getinspectionList = function(){
        if($scope.busy) return false;
        var path = url + '?page=' + $scope.page + '&limit=' + $scope.limit + '&key='; // '/device?page=1&limit=40';
        $scope.busy = true;
        httpService.request("GET", path, null, function(result){
            //$scope.deviceList = result.data;
            if(!result.success){
                toaster.error(result.message);
            }
            angular.forEach(result.data, function(data, i){
                $scope.inspectionList.push(data);
            });
            if(result.data.length >= $scope.limit){
                $scope.busy = false;
                $scope.page += 1;
            }
            if($scope.inspectionList.length > 0 && $scope.isGetDetailTag){
                $scope.isGetDetailTag = false;
                var arr = $scope.inspectionList;
                $scope.activeId = arr[0].Id;//默认查询第一条记录的详情
            }
        });
    }
    //获取任务详情
    $scope.getinspectionDetail = function(Id, isRgt){
        var path = url + '/' + Id;
        httpService.request("GET", path, null, function(result){
            var _DeviceId = _.map(result.data.Items, function(item){return item.TargetId });//得到关联设施id数组
            var _DeviceName = _.map(result.data.Items, function(item){return item.TargetCode });//得到关联设施name数组
            var _Points = _.map(result.data.Items,
                function(item){

                    return {x : item.TargetLng, y : item.TargetLat};
                });//得到关联设施name数组

            //  var _Points = _.map(result.data.Items, function(item){return {x : item.TargetLng, y : itme.TargetLat} });
            //do some test
            //


            $scope.position = _Points;//显示被选择的点信息
            if(isRgt){

                $scope.inspectionDetailModel = result.data;
                $scope.inspectionDetailModel.DeviceId = _DeviceId;
                $scope.inspectionDetailModel.DeviceName = _DeviceName;
            } else {
                $scope.inspectionModel = result.data;
                $scope.inspectionModel.DeviceId = _DeviceId;
                $scope.inspectionModel.DeviceName = _DeviceName;
            }
        });
    }
    //获取用户列表
    $scope.getUserList = function(){
        var path = '/user?page=1';
        httpService.request("GET", path, null, function(result){
            $scope.userList = result.data;
        });
    }
    //获取右侧model
    $scope.getRgtModel = function(){
        //点击列表重置查询参数
        if(!$scope.activeId){
            return
        }
        $scope.getinspectionDetail($scope.activeId, true);//获取巡查任务详情
    }
    /*业务类*/
    //派发任务
    $scope.mission = function(item){
        if(item.MissionStatus == 1)
            return
        var path = "/mission/push/" + item.Id;
        httpService.request("put", path, {HandlerId : item.HandlerId}, function(result){
                item.MissionStatus = 1;
                toaster.pop("success", "提示", result.message);
            }
        )
    }


    //$scope.selecedresults = [];
    //打开选点地图
    $scope.openDeviceSelect = function(){
        $scope.pointselectOption.initialayer = true;

        $('#deviceSelectModal').modal('show');
    }
    //关闭选点地图
    $scope.closeDeviceSelect = function(){
        //开始赋值给modal
        var _results = $scope.pointselectOption.selecedresults;

        $scope.inspectionModel.DeviceId = _results.map(function(item){
            return item.attributes.id;
        });
        $scope.inspectionModel.DeviceName = _results.map(function(item){
            return item.attributes.code;
        });
        $('#deviceSelectModal').modal('hide');
    }

    // 地图选择点配置信息
    $scope.pointselectOption = {
        //初始化图标
        toolItems : [
            //{ itemName: "Point", title: "点拾取", imgName: "D_点拾取.png"},
            {itemName : "Rectangle", title : "矩形拾取", imgName : "D_矩形拾取.png"},
            {itemName : "Polygon", title : "多边形拾取", imgName : "D_多边形拾取.png"}
        ],
        //展示底图图层
        pointLayers : [
            {
                lyrServerid : "1",
                layerName : "设备点",
                layerFilter : "",
                visibility : true,
                isDraw : false,
                featuresData : []
            }
          ],
        initialayer : false,
        //查询结果
        selecedresults : []
    }

    //地图设置位置信息
    $scope.setLocationOption = {
        mapid : "setLocation",
        center : {x : 155307.451, y : 139762.144, lng : 0, lat : 0},
        zoom : 0,
        height : 500,
        showgdmap : false
    };

    //地图高度
    $scope.mapheight = 400;

    $scope.mapIntialed = function($scope){

        //初始化地图操作对象(基于此对象操作地图元素)
        var mapobj = $scope.$$childHead.mapinstance;


        mapobj.addDynamicMap($rootScope.arcgisConfig.baseMap);


        mapobj.addFeatureLayer("设备点", {
            maxScale : 0, minScale : 0, showInfoTemplate : false,
            definitionExpression : "unitid=" + $localStorage.userInfo.unitid
        });

    };

    
    $scope.initParam();// 初始化查询列表变量
    $scope.getinspectionList();//获取任务列表
    $scope.getUserList();//获取用户列表
});

